import requests
import argparse


class ApiClient:
    def __init__(self, base_url):
        self.base_url = base_url

    def get(self, endpoint, params=None, headers=None):
        url = f"{self.base_url}/{endpoint}"
        try:
            response = requests.get(url, params=params, headers=headers)
            response.raise_for_status()  # 检查请求是否成功
            return response.json()  # 假设返回的内容是 JSON 格式
        except requests.RequestException as e:
            print(f"GET请求失败: {e}")
            return None

    def post(self, endpoint, data=None, json=None, headers=None):
        url = f"{self.base_url}/{endpoint}"
        try:
            response = requests.post(url, data=data, json=json, headers=headers)
            response.raise_for_status()  # 检查请求是否成功
            return response.json()  # 假设返回的内容是 JSON 格式
        except requests.RequestException as e:
            print(f"POST请求失败: {e}")
            return None

    def background_sendSms(self, account, password, authCode):

        get_response = self.post("moyin-admin-service/sys/sendSms",
                                 data={"account": account, "password": password,
                                       "authCode": authCode})
        return get_response

    def background_login(self, account, password, authCode):

        get_response = self.post("moyin-admin-service/sys/login",
                                 data={"account": account, "password": password,
                                       "authCode": authCode})
        return get_response

    def updateAppVersion(self, appname, version, needUpdateRange, channel, forceUpdate, needGrayScale, versionDesc):
        self.background_sendSms('admin', 'e10adc3949ba59abbe56e057f20f883e', '111111')
        token = self.background_login('admin', 'e10adc3949ba59abbe56e057f20f883e', '111111')['data']['token']

        adddata = {
            'os': 'android',
            'version': version,
            'needUpdateRange': f'{needUpdateRange}',
            'channel': channel,
            'url': f'https://img.ah-suuwaa.com/apk/{appname}_{channel}-apk',
            'forceUpdate': forceUpdate,
            'needGrayScale': needGrayScale,
            'versionDesc': versionDesc
        }

        get_response = self.post('moyin-admin-service/appVersion/add',
                                 data=adddata,
                                 headers={'token': token})
        return get_response

    def str_to_bool(self, value):
        # 处理字符串到布尔值的转换
        if isinstance(value, str):
            value = value.lower()
            if value in ('True', 'true', '1', 'yes', 'y'):
                return True
            elif value in ('False', 'false', '0', 'no', 'n'):
                return False
        return False  # 默认返回 False


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="配置app更新")
    parser.add_argument("appname", type=str, help="app名字")
    parser.add_argument("version", type=str, help="更新的版本号")
    parser.add_argument("needUpdateRange", type=str, help="更新的范围版本")
    parser.add_argument("channel", type=str, help="更新的渠道")
    parser.add_argument("forceUpdate", type=str, help="是否强更")
    parser.add_argument("needGrayScale", type=str, help="是否灰度")
    parser.add_argument("versionDesc", type=str, help="更新文案")
    parser.add_argument("url_type", type=str, help="选择的 URL 类型")  # 新增字段

    args = parser.parse_args()

    # 根据 url_type 选择不同的 base_url
    if args.url_type == "在身边":
        base_url = "https://bltest.ah-suuwaa.com/api"
    elif args.url_type == "懂你":
        base_url = "https://yjzqtest.gxqianxu.com/api"
    else:
        raise ValueError("未知的 url_type: {}".format(args.url_type))

    client = ApiClient(base_url)

    # 使用函数转换字符串到布尔值
    forceUpdate = client.str_to_bool(args.forceUpdate)
    needGrayScale = client.str_to_bool(args.needGrayScale)

    client.updateAppVersion(args.appname, args.version, args.needUpdateRange, args.channel, args.forceUpdate, args.needGrayScale,
                            args.versionDesc)

    # client.updateAppVersion(appname='zsb', version='2.4.6', channel='official9', forceUpdate=False, needGrayScale=False,
    #                         versionDesc='测试\n下班咯')
